<template>
	<view class="detail-container">
		<!-- 设备信息头部 -->
		<view class="device-header">
			<view class="device-icon">
				<text class="icon">📱</text>
			</view>
			<view class="device-info">
				<text class="device-name">{{ deviceInfo.name || '未知设备' }}</text>
				<text class="device-id">{{ deviceInfo.deviceId }}</text>
				<text class="device-status">状态: {{ getDeviceStatus() }}</text>
			</view>
		</view>
		
		<!-- 切换按钮区域 -->
		<view class="switch-section">
			<text class="section-title">设备控制</text>
			<view class="switch-container">
				<view class="switch-button" @tap="sendCommand">
					<text class="button-text">发送指令</text>
					<text class="button-desc">点击发送字符串 "1" 给设备</text>
				</view>
				<view class="command-history">
					<text class="history-title">发送历史</text>
					<scroll-view class="history-list" scroll-y>
						<view 
							v-for="(item, index) in commandHistory" 
							:key="index" 
							class="history-item"
						>
							<text class="history-time">{{ formatTime(item.timestamp) }}</text>
							<text class="history-command">指令: "{{ item.command }}"</text>
							<text class="history-status" :class="{ success: item.success }">
								{{ item.success ? '✓ 发送成功' : '✗ 发送失败' }}
							</text>
						</view>
						<view class="empty-history" v-if="commandHistory.length === 0">
							<text class="empty-text">暂无发送记录</text>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="back-btn" @tap="goBack">
				返回个人中心
			</button>
			<button class="disconnect-btn" @tap="disconnectDevice">
				断开连接
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				deviceInfo: {},
				commandHistory: [],
				serviceId: null,
				characteristicId: null
			}
		},
		
		onLoad(options) {
			if (options.device) {
				this.deviceInfo = JSON.parse(options.device)
                console.log('deviceInfo:', this.deviceInfo)
				this.initDevice()
			}
		},
		
		methods: {
			// 初始化设备
			async initDevice() {
				uni.showLoading({
					title: '初始化设备...'
				})
				
				try {
					// 获取设备服务
					const services = await uni.getBLEDeviceServices({
						deviceId: this.deviceInfo.deviceId
					})
					
					if (services.services && services.services.length > 0) {
						// 尝试所有服务，直到找到可写的特征
						let foundWriteChar = false
						
						for (const service of services.services) {
							this.serviceId = service.uuid
							
							try {
								// 获取服务特征
								const characteristics = await uni.getBLEDeviceCharacteristics({
									deviceId: this.deviceInfo.deviceId,
									serviceId: this.serviceId
								})
								
								if (characteristics.characteristics && characteristics.characteristics.length > 0) {
									// 寻找可写的特征
									const writeChar = characteristics.characteristics.find(char => 
										char.properties.write || char.properties.writeWithoutResponse
									)
									
									if (writeChar) {
										this.characteristicId = writeChar.uuid
										console.log('找到可写特征:', this.characteristicId)
										foundWriteChar = true
										break // 找到可写特征，跳出循环
									}
								}
							} catch (error) {
								console.warn('获取服务特征失败:', error)
								continue // 继续尝试下一个服务
							}
						}
						
						if (!foundWriteChar) {
							console.warn('未找到任何可写特征')
						}
					} else {
						console.warn('未找到任何蓝牙服务')
					}
					
					uni.hideLoading()
					
					if (this.serviceId && this.characteristicId) {
						uni.showToast({
							title: '设备初始化完成',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: '设备可能不支持写入',
							icon: 'none',
							duration: 3000
						})
					}
					
				} catch (error) {
					console.error('设备初始化失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '设备初始化失败',
						icon: 'none'
					})
				}
			},
			
			// 发送指令给设备
			async sendCommand() {
				if (!this.serviceId || !this.characteristicId) {
					uni.showToast({
						title: '设备未就绪，请检查初始化',
						icon: 'none',
						duration: 3000
					})
					console.log('发送失败 - 服务ID:', this.serviceId, '特征ID:', this.characteristicId)
					return
				}
				
				try {
					uni.showLoading({
						title: '发送中...'
					})
					
					// 检查蓝牙连接状态
					const { connected } = await uni.getConnectedBluetoothDevices()
					const deviceConnected = connected.some(device => device.deviceId === this.deviceInfo.deviceId)
					
					if (!deviceConnected) {
						throw new Error('设备已断开连接')
					}
					
					// 将字符串 "1" 转换为 ArrayBuffer
					const encoder = new TextEncoder()
					const data = encoder.encode("1")
					
					console.log('准备发送数据:', {
						deviceId: this.deviceInfo.deviceId,
						serviceId: this.serviceId,
						characteristicId: this.characteristicId,
						data: data
					})
					
					// 发送数据
					await uni.writeBLECharacteristicValue({
						deviceId: this.deviceInfo.deviceId,
						serviceId: this.serviceId,
						characteristicId: this.characteristicId,
						value: data.buffer
					})
					
					// 记录发送历史
					this.addToHistory("1", true)
					
					uni.hideLoading()
					uni.showToast({
						title: '指令发送成功',
						icon: 'success'
					})
					
				} catch (error) {
					console.error('发送指令失败:', error)
					
					// 记录失败历史
					this.addToHistory("1", false)
					
					uni.hideLoading()
					
					let errorMessage = '发送失败'
					if (error.errMsg) {
						if (error.errMsg.includes('not connected')) {
							errorMessage = '设备已断开连接'
						} else if (error.errMsg.includes('write characteristic')) {
							errorMessage = '写入特征失败'
						} else if (error.errMsg.includes('BLE Error')) {
							errorMessage = '蓝牙通信错误'
						}
					}
					
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					})
				}
			},
			
			// 添加到历史记录
			addToHistory(command, success) {
				const historyItem = {
					command: command,
					success: success,
					timestamp: new Date().getTime()
				}
				
				this.commandHistory.unshift(historyItem)
				
				// 限制历史记录数量
				if (this.commandHistory.length > 10) {
					this.commandHistory = this.commandHistory.slice(0, 10)
				}
				
				// 保存到本地存储
				try {
					const key = `commandHistory_${this.deviceInfo.deviceId}`
					uni.setStorageSync(key, this.commandHistory)
				} catch (error) {
					console.error('保存历史记录失败:', error)
				}
			},
			
			// 断开设备连接
			async disconnectDevice() {
				uni.showModal({
					title: '断开连接',
					content: '确定要断开此设备的连接吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '断开中...'
								})
								
								await uni.closeBLEConnection({
									deviceId: this.deviceInfo.deviceId
								})
								
								// 更新全局连接设备列表
								this.updateGlobalDevices()
								
								uni.hideLoading()
								uni.showToast({
									title: '已断开连接',
									icon: 'success'
								})
								
								// 返回上一页
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
								
							} catch (error) {
								console.error('断开连接失败:', error)
								uni.hideLoading()
								uni.showToast({
									title: '断开失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			// 更新全局设备列表
			updateGlobalDevices() {
				try {
					let connectedDevices = uni.getStorageSync('connectedDevices') || []
					connectedDevices = connectedDevices.filter(
						d => d.deviceId !== this.deviceInfo.deviceId
					)
					uni.setStorageSync('connectedDevices', connectedDevices)
					
					// 添加到历史记录
					this.addToHistoryDevice(this.deviceInfo)
					
				} catch (error) {
					console.error('更新设备列表失败:', error)
				}
			},
			
			// 添加到历史设备
			addToHistoryDevice(device) {
				try {
					let history = uni.getStorageSync('historyDevices') || []
					history = history.filter(d => d.deviceId !== device.deviceId)
					history.unshift({
						...device,
						lastConnectTime: new Date().getTime()
					})
					if (history.length > 50) {
						history = history.slice(0, 50)
					}
					uni.setStorageSync('historyDevices', history)
				} catch (error) {
					console.error('保存历史设备失败:', error)
				}
			},
			
			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '未知时间'
				const date = new Date(timestamp)
				const now = new Date()
				const diff = now - date
				
				if (diff < 60000) {
					return '刚刚'
				} else if (diff < 3600000) {
					return Math.floor(diff / 60000) + '分钟前'
				} else if (diff < 86400000) {
					return Math.floor(diff / 3600000) + '小时前'
				} else {
					return date.getMonth() + 1 + '月' + date.getDate() + '日'
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 获取设备状态
			getDeviceStatus() {
				if (this.serviceId && this.characteristicId) {
					return '已连接 - 可发送指令'
				} else if (this.serviceId && !this.characteristicId) {
					return '已连接 - 不支持写入'
				} else {
					return '已连接 - 初始化中'
				}
			}
		}
	}
</script>

<style scoped>
	.detail-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	/* 设备头部 */
	.device-header {
		display: flex;
		align-items: center;
		background: white;
		padding: 40rpx 30rpx;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.device-icon {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		overflow: hidden;
		margin-right: 30rpx;
		background: linear-gradient(135deg, #007AFF, #5856D6);
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.icon {
		font-size: 50rpx;
		color: white;
	}
	
	.device-info {
		flex: 1;
	}
	
	.device-name {
		display: block;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.device-id {
		display: block;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 5rpx;
	}
	
	.device-status {
		display: block;
		font-size: 24rpx;
		color: #4cd964;
	}
	
	/* 切换区域 */
	.switch-section {
		background: white;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.section-title {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.switch-container {
		padding: 30rpx;
	}
	
	.switch-button {
		background: linear-gradient(135deg, #007AFF, #5856D6);
		border-radius: 20rpx;
		padding: 40rpx;
		text-align: center;
		color: white;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 15rpx rgba(0,122,255,0.3);
	}
	
	.switch-button:active {
		transform: scale(0.98);
		box-shadow: 0 2rpx 8rpx rgba(0,122,255,0.3);
	}
	
	.button-text {
		display: block;
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 15rpx;
	}
	
	.button-desc {
		display: block;
		font-size: 24rpx;
		opacity: 0.9;
	}
	
	/* 命令历史 */
	.command-history {
		background: #f8f9fa;
		border-radius: 15rpx;
		padding: 25rpx;
	}
	
	.history-title {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.history-list {
		max-height: 300rpx;
	}
	
	.history-item {
		background: white;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 15rpx;
		border-left: 6rpx solid #007AFF;
	}
	
	.history-item:last-child {
		margin-bottom: 0;
	}
	
	.history-time {
		display: block;
		font-size: 22rpx;
		color: #999;
		margin-bottom: 5rpx;
	}
	
	.history-command {
		display: block;
		font-size: 26rpx;
		color: #333;
		margin-bottom: 5rpx;
	}
	
	.history-status {
		display: block;
		font-size: 22rpx;
		color: #ff3b30;
	}
	
	.history-status.success {
		color: #4cd964;
	}
	
	.empty-history {
		text-align: center;
		padding: 40rpx;
		color: #999;
	}
	
	.empty-text {
		font-size: 26rpx;
	}
	
	/* 操作按钮 */
	.action-buttons {
		display: flex;
		gap: 20rpx;
	}
	
	.back-btn, .disconnect-btn {
		flex: 1;
		background-color: #007AFF;
		color: white;
		border-radius: 10rpx;
		font-size: 28rpx;
		padding: 25rpx;
	}
	
	.disconnect-btn {
		background-color: #ff3b30;
	}
</style>